import lodash from 'lodash';
import { getAlertJobInfo, updateJob } from '../services/alarm-job-controller';

export default {
  namespace: 'JobUpdateModel',

  state: {
    name: '...',
    // 基本配置
    addJobConfigData: {
      name: undefined,
      cron: '*/5 * * * * ?',
      rule: 'any',
      frequencyTimeLength: undefined,
      frequencyTimeLengthUnit: undefined,
      frequencyCountMax: undefined,
      flatlineTimeLengthMax: undefined,
      flatlineTimeLengthMaxUnit: undefined,
      description: undefined,
    },
    // 监控项
    esMetricDataList: [],
    // 告警通知
    notificationConfigList: [],
  },

  effects: {
    *getAlertJobInfo({ payload }, { call, put }) {
      const { name } = payload;
      // 请求数据
      const { alertConfig, jobBriefInfo } = yield call(getAlertJobInfo, name);
      if (!alertConfig) return;
      const addJobConfigData = {};
      addJobConfigData.name = alertConfig.name;
      addJobConfigData.cron = jobBriefInfo.cron;
      addJobConfigData.rule = alertConfig.notificationRule.rule;
      addJobConfigData.frequencyTimeLength = alertConfig.notificationRule.frequencyTimeLength;
      addJobConfigData.frequencyTimeLengthUnit = alertConfig.notificationRule.frequencyTimeLengthUnit;
      addJobConfigData.frequencyCountMax = alertConfig.notificationRule.frequencyCountMax;
      addJobConfigData.flatlineTimeLengthMax = alertConfig.notificationRule.flatlineTimeLengthMax;
      addJobConfigData.flatlineTimeLengthMaxUnit = alertConfig.notificationRule.flatlineTimeLengthMaxUnit;
      addJobConfigData.description = jobBriefInfo.description;
      const esMetricDataList = [];
      lodash.forEach(alertConfig.metricDataList, ({ metricTitle, queryParams: { body, method, path }, expectValues }) => {
        if (path) {
          esMetricDataList.push({ metricTitle, body, method, path, expectValues });
        }
      });
      // 保存数据
      yield put({ type: 'save', payload: { name, addJobConfigData, esMetricDataList, notificationConfigList: alertConfig.notificationConfigList } });
    },

    *updateJob({ payload, successCallBack }, { call, put }) {
      // 请求数据
      const result = yield call(updateJob, payload.name, payload);
      if (!result) return;
      // 刷新数据
      yield put({ type: 'save', payload: { esMetricDataList: [], notificationConfigList: [] } });
      if (successCallBack instanceof Function) successCallBack(result);
    },
  },

  reducers: {
    save(state, { payload }) {
      return { ...state, ...payload };
    },
  },
};
